package com.gec.filter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class AuthorFilter extends BaseFilter {

	// [1] "normal" ----> "/User/A", "/User/B"
	// [2] "admin" ----> "/User/C", "/User/D"
	Map<String, Set<String>> permMap = new HashMap();

	@Override
	protected void init() {
		String norPerm = getInitParameter("MENU_1");
		norPerm = delSpace(norPerm);
		String[] SP = norPerm.split(",");
		Set normalset = new HashSet();
		permMap.put("MENU_1", normalset);
		for (String p : SP) {
			normalset.add(p);
			System.out.println("[酒店经理]权限:" + p);
		}
		String adPerm = getInitParameter("MENU_*");
		adPerm = delSpace(adPerm);
		SP = adPerm.split(",");
		Set adminSet = new HashSet();
		permMap.put("MENU_*", adminSet);
		for (String p : SP) {
			adminSet.add(p);
			System.out.println("[管理员]权限:" + p);
		}
	}

	String delSpace(String line) {
		line = line.replaceAll("\t", "");
		line = line.replaceAll(" ", "");
		line = line.replaceAll("\r\n", "");
		line = line.replaceAll("\n", "");
		return line;
	}

	@Override
	protected void doFilter(HttpServletRequest req, HttpServletResponse resp, FilterChain chain)
			throws IOException, ServletException {
		String ctxPath = req.getContextPath();
		// {1}先获取到 URI, 但是 URI 中也会包含根地址。
		// {2}把根地址去除 ---> 去除[/AuthorityWeb]
		String URI = req.getRequestURI().replace(ctxPath, "");
		HttpSession session = req.getSession();
		// {3}从会话中取出 MENU_KEY 。
		String level = (String) session.getAttribute("MENU_KEY");
		// {1}从 map 中获取对应角色的权限。
		Set<String> pSet = permMap.get(level);
		if (pSet != null) {
			// {2}你的权限表中是否包含有这个【 URI 】地址。
			// 如正在访问: /User/editUser
			boolean isOK = pSet.contains(URI);
			if (isOK) { // 如果存在则 ---> 放行该请求。
				chain.doFilter(req, resp);
				return; // 退出方法。
			}
		}
		if(level.equals("MENU_*")) {
			level="你的level为:【管理员】";
		}else if(level.equals("MENU_1")) {
			level="你的level为:【酒店经理】";
		}
		level = URLEncoder.encode(level,  "UTF-8");
		System.out.println("【可访问的地址】:"+pSet);
		// {ps}其它情况则来到这里。
		resp.sendRedirect(ctxPath + "/Common/level?result="+level);
	}

}
